package utilities.tcpserver;

import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Vector;
import utilities.events.event;

public class managed
	extends utilities.events.dispatcher
	implements utilities.events.listener
{
	protected unmanaged server;
	protected Vector<session> sessions;
	
	protected void addClient(Object client)
	{
		session session = (session)client;
		
		session.addListener(this);
		sessions.add(session);
	}
	
	protected void removeClient(Object client)
	{
		session session = (session)client;
		
		session.removeListener(this);
		sessions.remove(session);
	}
	
	protected void finalize() throws Throwable
	{
		server.removeListener(this);
		removeClients();
		super.finalize();
	}
	
	public managed(String hostname, int port)
	{
		sessions = new Vector<session>();
		
		server = new unmanaged(new InetSocketAddress(hostname, port));
		server.addListener(this);
	}
	
	public managed(int port)
	{
		this("localhost", port);
	}
	
	public void start()
	{
		server.start();
	}
	
	public void removeClients()
	{
		Iterator<session> itr = sessions.iterator();
		while(itr.hasNext())
		{
			((session)itr.next()).close();
			itr = sessions.iterator();
		}
		
		sessions.removeAllElements();
	}
	
	public void eventOccurred(event evt)
	{
		utilities.tcpserver.events.event event = (utilities.tcpserver.events.event)evt;
		utilities.tcpserver.events.event.EventCodes eventCode = event.getEventCode();
		
		if (eventCode == utilities.tcpserver.events.event.EventCodes.SESSION_OPENED)
			addClient(event.getObj());
		else if (eventCode == utilities.tcpserver.events.event.EventCodes.SESSION_CLOSED)
			removeClient(event.getObj());
		else if (eventCode == utilities.tcpserver.events.event.EventCodes.MESSAGE_RECIVED)
			fireEvent(new utilities.events.event(event.getSource(), event.getObj()));
	}
}
